use serde::{Deserialize, Serialize};
use super::IndicatorResult;

/// 趋势强度级别
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum TrendStrength {
    /// 极强趋势
    VeryStrong,
    /// 强趋势
    Strong,
    /// 中等趋势
    Moderate,
    /// 弱趋势
    Weak,
    /// 无明显趋势
    None,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_data() -> (IndicatorResult, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) {
        let prices = vec![100.0, 102.0, 101.0, 103.0, 102.5, 104.0, 105.0];
        let volumes = vec![1000.0, 1200.0, 900.0, 1100.0, 1300.0, 1400.0, 1500.0];
        let high_prices = vec![101.0, 103.0, 102.0, 104.0, 103.5, 105.0, 106.0];
        let low_prices = vec![99.0, 101.0, 100.0, 102.0, 101.5, 103.0, 104.0];
        
        let indicators = IndicatorResult {
            sma: std::collections::HashMap::new(),
            ema: std::collections::HashMap::new(),
            rsi: vec![50.0, 55.0, 45.0, 60.0, 58.0, 65.0, 70.0],
            macd_line: vec![0.1, 0.2, 0.15, 0.25, 0.3, 0.35, 0.4],
            macd_signal: vec![0.12, 0.18, 0.16, 0.22, 0.28, 0.32, 0.38],
            macd_histogram: vec![-0.02, 0.02, -0.01, 0.03, 0.02, 0.03, 0.02],
            adx: vec![20.0, 22.0, 23.0, 25.0, 27.0, 30.0, 32.0],
            bb_upper: vec![102.0, 104.0, 103.0, 105.0, 104.5, 106.0, 107.0],
            bb_middle: vec![100.0, 102.0, 101.0, 103.0, 102.5, 104.0, 105.0],
            bb_lower: vec![98.0, 100.0, 99.0, 101.0, 100.5, 102.0, 103.0],
            mfi: vec![45.0, 50.0, 48.0, 55.0, 60.0, 65.0, 70.0],
            atr: vec![2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6],
        };

        (indicators, prices, volumes, high_prices, low_prices)
    }

    #[test]
    fn test_market_analysis() {
        let mut analyzer = MarketStateAnalyzer::default();
        let (indicators, prices, volumes, high_prices, low_prices) = create_test_data();

        let analysis = analyzer.analyze_market(&indicators, &prices, &volumes, &high_prices, &low_prices);

        // 验证分析结果
        assert!(matches!(analysis.state, MarketState::Overbought));
        assert!(matches!(analysis.trend_strength, TrendStrength::Strong));
        assert!(analysis.volume_confirms_trend);
    }

    #[test]
    fn test_pivot_levels() {
        let analyzer = MarketStateAnalyzer::default();
        let pivot_levels = analyzer.calculate_pivot_levels(105.0, 95.0, 100.0);

        assert!(pivot_levels.resistance1 > pivot_levels.pivot);
        assert!(pivot_levels.support1 < pivot_levels.pivot);
    }

    #[test]
    fn test_market_sentiment() {
        let analyzer = MarketStateAnalyzer::default();
        let sentiment = analyzer.calculate_market_sentiment(75.0, 0.5, 0.03);
        assert!(matches!(sentiment, MarketSentiment::Greed));
    }
}

/// 价格动量状态
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum MomentumState {
    /// 强势上涨
    StrongUp,
    /// 温和上涨
    ModerateUp,
    /// 盘整
    Sideways,
    /// 温和下跌
    ModerateDown,
    /// 强势下跌
    StrongDown,
}

/// 市场情绪
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum MarketSentiment {
    /// 极度贪婪
    ExtremeGreed,
    /// 贪婪
    Greed,
    /// 中性
    Neutral,
    /// 恐惧
    Fear,
    /// 极度恐惧
    ExtremeFear,
}

/// 市场状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MarketState {
    /// 强烈看涨
    StrongBullish,
    /// 看涨
    Bullish,
    /// 轻度看涨
    MildlyBullish,
    /// 中性
    Neutral,
    /// 轻度看跌
    MildlyBearish,
    /// 看跌
    Bearish,
    /// 强烈看跌
    StrongBearish,
    /// 过度买入
    Overbought,
    /// 过度卖出
    Oversold,
    /// 高波动
    HighVolatility,
    /// 低波动
    LowVolatility,
    /// 趋势转换
    TrendReversal,
    /// 突破
    Breakout,
    /// 未知
    Unknown,
}

impl std::fmt::Display for MarketState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MarketState::StrongBullish => write!(f, "强烈看涨"),
            MarketState::Bullish => write!(f, "看涨"),
            MarketState::MildlyBullish => write!(f, "轻度看涨"),
            MarketState::Neutral => write!(f, "中性"),
            MarketState::MildlyBearish => write!(f, "轻度看跌"),
            MarketState::Bearish => write!(f, "看跌"),
            MarketState::StrongBearish => write!(f, "强烈看跌"),
            MarketState::Overbought => write!(f, "过度买入"),
            MarketState::Oversold => write!(f, "过度卖出"),
            MarketState::HighVolatility => write!(f, "高波动"),
            MarketState::LowVolatility => write!(f, "低波动"),
            MarketState::TrendReversal => write!(f, "趋势转换"),
            MarketState::Breakout => write!(f, "突破"),
            MarketState::Unknown => write!(f, "未知"),
        }
    }
}

/// 支撑阻力位
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PivotLevel {
    /// 阻力位3
    pub resistance3: f64,
    /// 阻力位2
    pub resistance2: f64,
    /// 阻力位1
    pub resistance1: f64,
    /// 轴心点
    pub pivot: f64,
    /// 支撑位1
    pub support1: f64,
    /// 支撑位2
    pub support2: f64,
    /// 支撑位3
    pub support3: f64,
}

/// 市场分析结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketAnalysis {
    /// 市场状态
    pub state: MarketState,
    /// 趋势强度
    pub trend_strength: TrendStrength,
    /// 价格动量
    pub momentum: MomentumState,
    /// 市场情绪
    pub sentiment: MarketSentiment,
    /// 支撑阻力位
    pub pivot_levels: PivotLevel,
    /// 成交量趋势确认
    pub volume_confirms_trend: bool,
}

/// 市场状态分析器
pub struct MarketStateAnalyzer {
    /// 过度买入RSI阈值
    overbought_rsi: f64,
    /// 过度卖出RSI阈值
    oversold_rsi: f64,
    /// 高波动BB宽度阈值
    high_volatility_bb_width: f64,
    /// 低波动BB宽度阈值
    low_volatility_bb_width: f64,
    /// 趋势强度ADX阈值
    strong_trend_adx: f64,
    /// 极强趋势ADX阈值
    very_strong_trend_adx: f64,
    /// 动量阈值
    momentum_threshold: f64,
    /// 成交量确认阈值（相对于平均成交量的倍数）
    volume_confirmation_threshold: f64,
    /// 缓存最近的分析结果
    cache: Option<(IndicatorResult, Vec<f64>, Vec<f64>, MarketAnalysis)>,
}

impl Default for MarketStateAnalyzer {
    fn default() -> Self {
        Self {
            overbought_rsi: 70.0,
            oversold_rsi: 30.0,
            high_volatility_bb_width: 0.05, // 相对于价格的5%
            low_volatility_bb_width: 0.01,  // 相对于价格的1%
            strong_trend_adx: 25.0,
            very_strong_trend_adx: 50.0,
            momentum_threshold: 0.02, // 2%的价格变动被视为显著
            volume_confirmation_threshold: 1.5, // 高于平均成交量50%
            cache: None,
        }
    }
}

impl MarketStateAnalyzer {
    /// 创建新的市场状态分析器
    pub fn new() -> Self {
        Self::default()
    }
    
    /// 检查缓存是否有效
    fn is_cache_valid(&self, indicators: &IndicatorResult, prices: &[f64], volumes: &[f64]) -> bool {
        if let Some((cached_indicators, cached_prices, cached_volumes, _)) = &self.cache {
            if cached_indicators.rsi.len() == indicators.rsi.len() && 
               cached_prices.len() == prices.len() &&
               cached_volumes.len() == volumes.len() {
                return cached_indicators.rsi.last() == indicators.rsi.last() && 
                       cached_prices.last() == prices.last() &&
                       cached_volumes.last() == volumes.last();
            }
        }
        false
    }

    /// 计算趋势强度
    fn calculate_trend_strength(&self, adx: f64) -> TrendStrength {
        if adx >= self.very_strong_trend_adx {
            TrendStrength::VeryStrong
        } else if adx >= self.strong_trend_adx {
            TrendStrength::Strong
        } else if adx >= 15.0 {
            TrendStrength::Moderate
        } else if adx >= 10.0 {
            TrendStrength::Weak
        } else {
            TrendStrength::None
        }
    }

    /// 计算价格动量状态
    fn calculate_momentum_state(&self, prices: &[f64], period: usize) -> MomentumState {
        if prices.len() < period {
            return MomentumState::Sideways;
        }

        let current_price = prices[prices.len() - 1];
        let past_price = prices[prices.len() - period];
        let price_change = (current_price - past_price) / past_price;

        if price_change > self.momentum_threshold * 2.0 {
            MomentumState::StrongUp
        } else if price_change > self.momentum_threshold {
            MomentumState::ModerateUp
        } else if price_change < -self.momentum_threshold * 2.0 {
            MomentumState::StrongDown
        } else if price_change < -self.momentum_threshold {
            MomentumState::ModerateDown
        } else {
            MomentumState::Sideways
        }
    }

    /// 计算市场情绪
    fn calculate_market_sentiment(&self, rsi: f64, macd_hist: f64, bb_width: f64) -> MarketSentiment {
        let sentiment_score = rsi * 0.4 + // RSI权重40%
                            (if macd_hist > 0.0 { 60.0 } else { 40.0 }) * 0.3 + // MACD柱状图权重30%
                            (bb_width * 1000.0).min(100.0) * 0.3; // 布林带宽度权重30%

        if sentiment_score >= 80.0 {
            MarketSentiment::ExtremeGreed
        } else if sentiment_score >= 60.0 {
            MarketSentiment::Greed
        } else if sentiment_score >= 40.0 {
            MarketSentiment::Neutral
        } else if sentiment_score >= 20.0 {
            MarketSentiment::Fear
        } else {
            MarketSentiment::ExtremeFear
        }
    }

    /// 计算支撑阻力位
    fn calculate_pivot_levels(&self, high: f64, low: f64, close: f64) -> PivotLevel {
        let pivot = (high + low + close) / 3.0;
        let range = high - low;

        PivotLevel {
            resistance3: pivot + range * 2.0,
            resistance2: pivot + range,
            resistance1: pivot * 2.0 - low,
            pivot,
            support1: pivot * 2.0 - high,
            support2: pivot - range,
            support3: pivot - range * 2.0,
        }
    }

    /// 检查成交量是否确认趋势
    fn volume_confirms_trend(&self, volumes: &[f64], prices: &[f64], period: usize) -> bool {
        if volumes.len() < period || prices.len() < period {
            return false;
        }

        let recent_volume = volumes[volumes.len() - 1];
        let avg_volume: f64 = volumes[volumes.len() - period..].iter().sum::<f64>() / period as f64;
        let price_change = prices[prices.len() - 1] - prices[prices.len() - 2];

        // 成交量高于平均值且价格变动方向一致时确认趋势
        recent_volume > avg_volume * self.volume_confirmation_threshold && 
        (price_change.abs() >= self.momentum_threshold * prices[prices.len() - 2])
    }
    
    /// 设置RSI过度买入阈值
    pub fn with_overbought_rsi(mut self, value: f64) -> Self {
        self.overbought_rsi = value;
        self
    }
    
    /// 设置RSI过度卖出阈值
    pub fn with_oversold_rsi(mut self, value: f64) -> Self {
        self.oversold_rsi = value;
        self
    }

    /// 设置强趋势ADX阈值
    pub fn with_strong_trend_adx(mut self, value: f64) -> Self {
        self.strong_trend_adx = value;
        self
    }

    /// 设置极强趋势ADX阈值
    pub fn with_very_strong_trend_adx(mut self, value: f64) -> Self {
        self.very_strong_trend_adx = value;
        self
    }

    /// 设置动量阈值
    pub fn with_momentum_threshold(mut self, value: f64) -> Self {
        self.momentum_threshold = value;
        self
    }

    /// 设置成交量确认阈值
    pub fn with_volume_confirmation_threshold(mut self, value: f64) -> Self {
        self.volume_confirmation_threshold = value;
        self
    }
    
    /// 分析市场状态
    pub fn analyze_market(&mut self, indicators: &IndicatorResult, prices: &[f64], volumes: &[f64], high_prices: &[f64], low_prices: &[f64]) -> MarketAnalysis {
        // 检查缓存是否有效
        if self.is_cache_valid(indicators, prices, volumes) {
            if let Some((_, _, _, analysis)) = &self.cache {
                return analysis.clone();
            }
        }
        if indicators.rsi.is_empty() || prices.is_empty() || volumes.is_empty() {
            return MarketAnalysis {
                state: MarketState::Unknown,
                trend_strength: TrendStrength::None,
                momentum: MomentumState::Sideways,
                sentiment: MarketSentiment::Neutral,
                pivot_levels: PivotLevel {
                    resistance3: 0.0,
                    resistance2: 0.0,
                    resistance1: 0.0,
                    pivot: 0.0,
                    support1: 0.0,
                    support2: 0.0,
                    support3: 0.0,
                },
                volume_confirms_trend: false,
            };
        }
        
        let idx = indicators.rsi.len() - 1;
        let price_idx = prices.len() - 1;
        
        // 获取最新指标值
        let rsi = indicators.rsi[idx];
        let macd = indicators.macd_line[idx];
        let macd_signal = indicators.macd_signal[idx];
        let macd_hist = indicators.macd_histogram[idx];
        let adx = indicators.adx[idx];
        
        // 获取布林带宽度
        let bb_width = if !indicators.bb_upper.is_empty() && !indicators.bb_lower.is_empty() {
            let upper = indicators.bb_upper[idx];
            let lower = indicators.bb_lower[idx];
            let middle = indicators.bb_middle[idx];
            
            if middle > 0.0 {
                (upper - lower) / middle
            } else {
                0.0
            }
        } else {
            0.0
        };
        
        // 计算基础市场状态
        let state = if rsi > self.overbought_rsi {
            MarketState::Overbought
        } else if rsi < self.oversold_rsi {
            MarketState::Oversold
        } else if bb_width > self.high_volatility_bb_width {
            MarketState::HighVolatility
        } else if bb_width < self.low_volatility_bb_width {
            MarketState::LowVolatility
        } else if adx > self.strong_trend_adx {
            if macd > 0.0 && macd > macd_signal {
                MarketState::StrongBullish
            } else if macd < 0.0 && macd < macd_signal {
                MarketState::StrongBearish
            } else {
                MarketState::Neutral
            }
        } else if macd > 0.0 {
            if macd > macd_signal && macd_hist > 0.0 {
                MarketState::Bullish
            } else {
                MarketState::MildlyBullish
            }
        } else if macd < 0.0 {
            if macd < macd_signal && macd_hist < 0.0 {
                MarketState::Bearish
            } else {
                MarketState::MildlyBearish
            }
        } else {
            MarketState::Neutral
        };

        // 计算趋势强度
        let trend_strength = self.calculate_trend_strength(adx);

        // 计算价格动量
        let momentum = self.calculate_momentum_state(prices, 14);

        // 计算市场情绪
        let sentiment = self.calculate_market_sentiment(rsi, macd_hist, bb_width);

        // 计算支撑阻力位
        let pivot_levels = self.calculate_pivot_levels(
            high_prices[price_idx],
            low_prices[price_idx],
            prices[price_idx]
        );

        // 检查成交量确认
        let volume_confirms = self.volume_confirms_trend(volumes, prices, 20);

        // 创建市场分析结果
        let analysis = MarketAnalysis {
            state,
            trend_strength,
            momentum,
            sentiment,
            pivot_levels,
            volume_confirms_trend: volume_confirms,
        };

        // 更新缓存
        self.cache = Some((
            indicators.clone(),
            prices.to_vec(),
            volumes.to_vec(),
            analysis.clone()
        ));

        analysis
    }
}